package com.jinhuhang.u2.invertmodule.adapter;

import android.annotation.TargetApi;
import android.content.Context;
import android.os.Build;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.util.Log;
import android.util.SparseArray;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.jinhuhang.u2.R;
import com.jinhuhang.u2.entity.ProductAndTenderEntity;
import com.jinhuhang.u2.util.MathUtils;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

/**
 * Created by caoxiaowei on 2017/8/23.
 */
public class ItemListAdapter extends BaseAdapter {

    List<ProductAndTenderEntity.BorrowListBean> mBorrowBeen=new ArrayList<>();
    LayoutInflater mLayoutInflater;
    Context mContext;
    //用于退出activity,避免countdown，造成资源浪费。
    private SparseArray<CountDownTimer> countDownCounters;
    int type;
    public ItemListAdapter(List<ProductAndTenderEntity.BorrowListBean> borrowBeen, Context context, int type){
        mBorrowBeen=borrowBeen;
        mLayoutInflater=LayoutInflater.from(context);
        mContext=context;
        this.type=type;
        this.countDownCounters = new SparseArray<>();
    }
    public void cancelAllTimers() {
        if (countDownCounters == null) {
            return;
        }
        Log.e("TAG",  "size :  " + countDownCounters.size());
        for (int i = 0, length = countDownCounters.size(); i < length; i++) {
            CountDownTimer cdt = countDownCounters.get(countDownCounters.keyAt(i));
            if (cdt != null) {
                cdt.cancel();
            }
        }
    }
    @Override
    public int getCount() {
        return mBorrowBeen.size();
    }

    @Override
    public Object getItem(int position) {
        return mBorrowBeen.get(position);
    }

    @Override
    public long getItemId(int position) {
        return 0;
    }

    @TargetApi(Build.VERSION_CODES.CUPCAKE)
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        HoldView holdView;
        if (convertView==null){
            holdView=new HoldView();
            convertView=mLayoutInflater.inflate(R.layout.view_item_tender,null);
            holdView.progress=(TextView)convertView.findViewById(R.id.progress);
            holdView.tenderimg=(ImageView)convertView.findViewById(R.id.imgtitle);
            holdView.tendername=(TextView)convertView.findViewById(R.id.tender_name);
            holdView.month=(TextView)convertView.findViewById(R.id.monthnums);
            holdView.yield=(TextView)convertView.findViewById(R.id.yield);
            holdView.money=(TextView)convertView.findViewById(R.id.money);
            holdView.lay=(LinearLayout)convertView.findViewById(R.id.lay1);
            holdView.lay2=(ImageView)convertView.findViewById(R.id.lay2);
            holdView.multiple=(TextView)convertView.findViewById(R.id.multiple);
        //    holdView.sign=(TextView)convertView.findViewById(R.id.sign1);
            holdView.sign1=(TextView)convertView.findViewById(R.id.sign1);
            holdView.btn=(TextView)convertView.findViewById(R.id.tender_btn);
            holdView.txt=(TextView)convertView.findViewById(R.id.txt_list);
            holdView.signtxt=(TextView)convertView.findViewById(R.id.signtxt);
            holdView.unitstr=(TextView)convertView.findViewById(R.id.unit_tender);
            holdView.show=0;
            convertView.setTag(holdView);

        }else {
            holdView=(HoldView)convertView.getTag();
        }
//        holdView.btn.setOnClickListener(new View.OnClickListener() {
//            @Override
//            public void onClick(View v) {
//                if (type==3) {
//                    EventBus.getDefault().post("creator");
//                }
//            }
//        });

        BigDecimal bigDecimal=new BigDecimal(Float.parseFloat(mBorrowBeen.get(position).getAccountYes())*100/Float.parseFloat(mBorrowBeen.get(position).getAccount()));
        holdView.progress.setText("已出借进度"+ bigDecimal.setScale(2,   BigDecimal.ROUND_HALF_UP).doubleValue()+"%");
long time = Long.parseLong(mBorrowBeen.get(position).getValidTimeStart()) - Long.parseLong(mBorrowBeen.get(position).getLocalTime());
//        Handler mHandler=new Handler(new Handler.Callback() {
//            @Override
//            public boolean handleMessage(Message msg) {
//                if (msg.what==1){
//                    holdView.btn.setText(msg.obj+"");
//                    holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_yellow);
//                }else{
//                    notifyDataSetChanged();
//                }
//                    return false;
//            }
//        });
        CountDownTimer countDownTimer = countDownCounters.get(holdView.btn.hashCode());
        //将前一个缓存清除
        if (countDownTimer != null) {
            countDownTimer.cancel();
        }
        if (time >0){
            countDownTimer = new CountDownTimer(time , 1000) {
                public void onTick(long millisUntilFinished) {
                    long hh = millisUntilFinished / 1000/(60*60);
                    long mm =   millisUntilFinished/ 1000%(60*60)/60;
                    long ss =  millisUntilFinished/ 1000%(60*60)%60;
                    holdView.btn.setText( hh + ":" + mm + ":" + ss);
                    holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_yellow);
                }
                public void onFinish() {
                    holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_red);
                    holdView.btn.setText("抢购中");
                }
            }.start();
            countDownCounters.put(holdView.btn.hashCode(), countDownTimer);

//           if (holdView.show==0){
//               holdView.show=1;
//            holdView.timer.schedule(new TimerTask() {
//                public void run() {
//                    Message message=mHandler.obtainMessage();
//                    if (holdView.time<1000){
//                        message.what=2;
//                        mHandler.sendMessage(message);
//                        holdView.timer.cancel();
//                        return;
//                    }
//                    holdView.time-=1000;
////                    if (mBorrowBeen.get(position).getTitle().equals("ceshi4")){
////                        holdView.time-=1000;
////                    }
//                    long hh = holdView.time / 1000/(60*60);
//                    long mm =   holdView.time / 1000%(60*60)/60;
//                    long ss =  holdView.time / 1000%(60*60)%60;
//
//
//            //        Log.i("wwwwww"+ holdView.time/1000+":"+holdView.time / 1000/(60*60)+":"+ (holdView.time / 1000%(60*60))%60,hh + ":" + mm + ":" + ss);
//                    message.obj=+ hh + ":" + mm + ":" + ss;
//                    message.what=1;
//                    mHandler.sendMessage(message);
//                }
//            }, 0, 1000);
//           }else {
//
//           }
        }
        holdView.money.setText(mBorrowBeen.get(position).getAccount()+"");

        holdView.tendername.setText(mBorrowBeen.get(position).getTitle());

        if (type==1){
            holdView.yield.setText(mBorrowBeen.get(position).getRangeApr()+"");
        }else {
            holdView.yield.setText(mBorrowBeen.get(position).getApr()+"");
        }
         if (type==3){//债权标
             holdView.unitstr.setVisibility(View.GONE);
             holdView.month.setText(mBorrowBeen.get(position).getRemainMsg()+"");
         //    holdView.month.setTextSize(15);
             holdView.signtxt.setText("剩余期限");
             holdView.txt.setText("拟支付年化率");
            holdView.sign1.setVisibility(View.GONE);
            holdView.tenderimg.setImageResource(R.drawable.zhaiquanzhuanrang_zhuanrangicon);
            holdView.lay.setVisibility(View.GONE);
       //     holdView.sign.setVisibility(View.GONE);
            holdView.lay2.setVisibility(View.VISIBLE);
        }else {
             holdView.sign1.setText("自动投标");
             if (mBorrowBeen.get(position).getTimeLimitType()==1){
                 holdView.unitstr.setText("个月");
             }else   if (mBorrowBeen.get(position).getTimeLimitType()==2){
                 holdView.unitstr.setText("年");
             }
             else   if (mBorrowBeen.get(position).getTimeLimitType()==3){
                 holdView.unitstr.setText("天");
             }
             int i=0;
             if (mBorrowBeen.get(position).getSort()!=10){
                 holdView.sign1.setVisibility(View.GONE);
             }else {
                 holdView.sign1.setVisibility(View.VISIBLE);
                 i=1;
             }
             holdView.month.setText(mBorrowBeen.get(position).getTimeLimit()+"");
             holdView.signtxt.setText("服务期限");
             holdView.txt.setText("拟支付年化率");
             if (position%2==0){
                 holdView.tenderimg.setImageResource(R.drawable.touzi_hot);
             }else {
                 holdView.tenderimg.setImageResource(R.drawable.touzi_new);
             }
             if (Double.parseDouble(mBorrowBeen.get(position).getVirtualMultiples())>0) {
                 String s=mBorrowBeen.get(position).getVirtualMultiples();
                 if(s.indexOf(".") > 0){
                     //正则表达
                     s = s.replaceAll("0+?$", "");//去掉后面无用的零
                     s = s.replaceAll("[.]$", "");//如小数点后面全是零则去掉小数点
                 }
                 holdView.multiple.setText(s + "");
                 holdView.lay.setVisibility(View.VISIBLE);
                 i=1;
             }else {
                 holdView.lay.setVisibility(View.GONE);
             }

        //    holdView.sign.setVisibility(View.VISIBLE);
             if (i==0){
                 holdView.lay2.setVisibility(View.VISIBLE);
             }else {
                 holdView.lay2.setVisibility(View.GONE);
             }
        }
        holdView.btn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
 //               TenderMsg msg=new TenderMsg();
//                msg.id=mBorrowBeen.get(position).getId();
//                msg.type=type;
//                EventBus.getDefault().post(msg);
                if (mProjectListener!=null)
                mProjectListener.jump(position);
            }
        });


        if (mBorrowBeen.get(position).getStatus()==1){
            holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_red);
            holdView.btn.setText("开放中");
//            if (holdView.time>0){//倒计时
//                holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_yellow);
//
//            }
        }else  if (mBorrowBeen.get(position).getStatus()==2){
            holdView.btn.setBackgroundResource(R.drawable.u_rectangle_blue);
            holdView.btn.setText("已满");

        }
//        if (bigDecimal.intValue()==100)
//        {
//            holdView.btn.setBackgroundResource(R.drawable.u_rectangle_blue);
//            holdView.btn.setText("已满标");
//        }
//        if (Float.parseFloat(mBorrowBeen.get(position).getAccountYes())==Float.parseFloat(mBorrowBeen.get(position).getAccount()))
//        {
//            holdView.btn.setBackgroundResource(R.drawable.u_rectangle_blue);
//            holdView.btn.setText("已满标");
//        }
        else  if (mBorrowBeen.get(position).getStatus()==3){
            holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_gally);
            holdView.btn.setText("服务中");

        }
        else  if (mBorrowBeen.get(position).getStatus()==5){
            holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_gally);
            holdView.btn.setText("服务结束");

        }
        else  if (mBorrowBeen.get(position).getStatus()==-2){
            holdView.btn.setBackgroundResource(R.drawable.u2_rectangle_gally);
            holdView.btn.setText("已流标");

        }

//         if (MathUtils.subtract(mBorrowBeen.get(position).getValidTimeEnd(),mBorrowBeen.get(position).getLocalTime())<=0)
//        {
//            holdView.btn.setBackgroundResource(R.drawable.u_rectangle_blue);
//            holdView.btn.setText("已满标");
//        }

        return convertView;
    }



    class HoldView{
        int show=0;
        Timer timer = new Timer();
        ImageView tenderimg;
        TextView tendername;
        TextView progress;
        TextView yield;
        TextView month;
        TextView money;
        LinearLayout lay;
        ImageView lay2;
        TextView multiple;
        TextView sign;
        TextView sign1;
        TextView btn;
        TextView txt;
        TextView signtxt;
        TextView unitstr;
  //      long time;
    }

    ProjectListener mProjectListener;
    public void setLinstener(ProjectListener projectListener){
        mProjectListener=projectListener;
    }
    public interface  ProjectListener{
        void jump(int pos);
    }
}
